package com.neusoft.dibuy.tyut.net.util;

import com.neusoft.dibuy.tyut.net.cfg.NetConfig;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

@Data
@AllArgsConstructor
public class File2NetTool  extends  Thread {
    private Socket socket;
    private String targerFilePath;

    @Override
    public void run() {
        File file =  new File(targerFilePath);
        InputStream is =null;
        FileOutputStream fos= null;
        try {
            if (file.exists()) {
                System.out.println("File2NetTool.run  存在！！！");
                return;
            }
              else  {
                    file.createNewFile();
                }
              fos =new FileOutputStream(file);
              is = socket.getInputStream();
            byte[] bs =new byte[NetConfig.MSG_LENGTH];
            while (true){
                int len = is.read(bs);
                if (len==-1){
                    break;
                }
                fos.write(bs,0,len);
//                强制输出
                fos.flush();
            }
        } catch (IOException e) {
                e.printStackTrace();

        }finally {
            try {
                if (is!=null)
                    is.close();
                if (fos!=null)
                    fos.close();
                socket.close();
            }
            catch (Exception e){

            }
        }


    }
}
